<?php
/**
 * Created by PhpStorm.
 * User: mengkang <i@mengkang.net>
 * Date: 2017/10/24 下午11:45
 */

define("ROOT", __DIR__);

include ROOT . "/web/mysql/DbConfig.php";
include ROOT . "/web/mysql/DbConnection.php";
include ROOT . "/web/mysql/SqlExecute.php";

$server = new swoole_server("127.0.0.1", 10000);
$server->on('connect', function ($server, $fd){
    echo "connection open: {$fd}\n";
});
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
    $data = json_decode($data,true);

    call_user_func_array(['Soa',$data['action']],[$data['data']]);

    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "connection close: {$fd}\n";
});
$server->start();


class Soa{

    public static function pushConfig($data){
        $sql = "select b.* from subscriber a,services b  where a.service=? and b.app_name=a.app_name";
        $list = SqlExecute::getAll($sql,[$data['service']]);
        var_dump($list);

        // 获取最新的配置
        $sql = "select * from services where name=?";
        $services = SqlExecute::getAll($sql,[$data['service']]);

        var_dump($services);

        //推送给个消费者
        foreach ($list as $item) {
            $client = new swoole_client(SWOOLE_SOCK_TCP);
            $client->connect($item['ip'], $item['notify_port'], 0.5);
            $msg = json_encode([
                'action' => 'configUpdate',
                'data' => $services,
            ]);
            $str = pack('N', strlen($msg)) . $msg;
            $client->send($str);
        }
    }

    public static function register(){

    }
}